package top.dzygod.config;

import com.alipay.api.msg.MsgHandler;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sun.rmi.log.LogHandler;
import top.dzygod.modules.mp.domain.WxMpConfig;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: dingziyuan
 * @Date: 2020/2/18/018 15:38
 * @Description: 公众号配置
 */
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpConfig.class)
public class WxMpConfiguration {
    private final WxMpConfig properties;

    @Bean
    public WxMpService wxMpService() throws WxErrorException {
        final List<WxMpConfig.MpConfig> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("yml添加下相关配置，注意别配错了！");
        }

        WxMpService service = new WxMpServiceImpl();
        service.setMultiConfigStorages(configs
                .stream().map(a -> {
                    WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
                    configStorage.setAppId(a.getAppId());
                    configStorage.setSecret(a.getSecret());
                    configStorage.setToken(a.getToken());
                    configStorage.setAesKey(a.getAesKey());
                    return configStorage;
                }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));

        return service;
    }

    @Bean
    public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
            return new WxMpMessageRouter(wxMpService);
    }

}
